<template>
  <div style="width: 100%;position: relative;" v-loading="loading">
    <div class="chart-type">
      <el-button :disabled="!json.length" v-if="chartType == 'category'" @click="changeChartType('pie')"
        class="el-icon-pie-chart"></el-button>
      <el-button :disabled="!json.length" v-if="chartType == 'pie'" @click="changeChartType('category')"
        class="el-icon-notebook-2"></el-button>
    </div>
    <div id="chart-container" style="width: 100%;min-height:400px;"></div>
    <div class="empty-text" style="position: absolute;" v-if="!loading && !json.length">暂无数据</div>
  </div>

</template>

<script>
import * as echarts from 'echarts';
import { debounce } from 'lodash';
import { mapState } from 'vuex';
import { getCategoryChartData, getPieChartData } from './config';

export default {
  name: 'Chart',
  props: ['loading'],

  data() {
    return {
      myChart: null,
      chartType: 'category',
      json: []
    }
  },
  computed: {
    ...mapState({
      sidebar: (state) => state.app.sidebar,
    }),
  },
  watch: {
    'sidebar.opened': function (val) {
      this.handleResize()
    }
  },

  activated() {
    window.addEventListener("resize", this.handleResize);
  },
  deactivated() {
    window.removeEventListener("resize", this.handleResize);
  },
  mounted() {
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (this.myChart) {
      this.myChart.dispose();
      this.myChart = null;
    }
  },
  methods: {
    handleResize: debounce(function () {
      this.myChart?.resize();
    }, 200),

    async changeChartType(type = 'category') {
      this.chartType = type;
      let option = null;
      if (this.myChart) {
        this.myChart.dispose();
      }
      await this.$nextTick();
      this.myChart = echarts.init(this.$el.querySelector('#chart-container'));
      switch (type) {
        case 'pie':
          option = getPieChartData(this.json)
          this.myChart.setOption(option)
          break;
        case 'category':
          option = getCategoryChartData(this.json);
          this.myChart.setOption(option)
          break;
      }
    },
    setData(json) {
      this.json = json;
      debugger
      this.changeChartType();
    }
  }
}
</script>

<style lang="scss" scoped>
.empty-text {
  position: absolute;
  z-index: 100;
  top: 40px;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-size: 12px;
  // box-shadow: 0 0 6px 1px rgba(0, 57, 100, .12);
  border: 1px solid #dfe6ec;
  background-color: #ffffff;
}
</style>
